/**
 * Created by haoran.shu on 2018/11/15 17:21.
 */
const router = new require('koa-router')();
const logger = require('log4js').getLogger('websocket');
const mongo = require('../dbs/mongodb');
const PythonShell = require('python-shell').PythonShell;
const config = require('../config');
const parseMore = require('../utils/json_parser');

function runWs(ws, tel, step) {
  let pythonRun;

  ws.on('message', (message) => {
    if (tel) {
      let params = JSON.parse(message);
      logger.info(step + ' tactics _id: ', params._id);
      let updateDoc = {
        code: params.code,
        product: params.product,
        time: params.time,
        update_time: Date.now()
      };
      logger.debug(params._id);
      mongo.upsetById('tactics', params._id, updateDoc)
        .then((n) => {
          let options = Object.assign({}, config.python, {
            args: [params._id, "GOLD5", "3000"],
            parser: parseMore
          });
          pythonRun = new PythonShell(config.pythonRunFiles[step], options); // 训练过程模拟
          pythonRun.on('message', function (message) {
            // received a message sent from the Python script (a simple "print" statement)
            ws.send(JSON.stringify(message));
          });

          // end the input stream and allow the process to exit
          pythonRun.end(function (err, code) {
            ws.send(JSON.stringify({"type":"message","exitcode":code}));
            if(err)
              ws.send(JSON.stringify({"type":"error","error":err}));
            ws.close();
          });
        })
        .catch(err => {
          logger.error(err);
          ws.send(JSON.stringify({"type":"error","error":err}));
          ws.close();
        });
    }
  });

  ws.on('close', () => {
    if (pythonRun) {
      pythonRun.terminate();
    }
  });
}

// 训练模型
router.all('/train', (ctx) => {
  let ws = ctx.websocket;

  // 验证是否登录
  let tel = ctx.session.tel;
  if (!tel) { // cookie
    tel = ctx.cookies.get('wsSignTel');
    if (tel) {
      ctx.session.tel = tel;
    } else {
      ws.send('{"type":-1, "errmsg":"auth_error"}');
    }
  }

  runWs(ctx.websocket, tel, 'train');
});

// 运行回测
router.all('/test', (ctx) => {
  let ws = ctx.websocket;

  // 验证是否登录
  let tel = ctx.session.tel;
  if (!tel) { // cookie
    tel = ctx.cookies.get('wsSignTel');
    if (tel) {
      ctx.session.tel = tel;
    } else {
      ws.send('{"type":-1, "errmsg":"auth_error"}');
    }
  }

  runWs(ws, tel, 'test');
});

module.exports = router;
